package org.multimedia.jolitorask.extension.calendar.util.timer;

import java.rmi.RemoteException;
import java.util.Calendar;

import javax.ejb.CreateException;
import javax.ejb.EJBException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.ejb.TimedObject;
import javax.ejb.Timer;
import javax.ejb.TimerService;
import javax.naming.InitialContext;

import org.multimedia.jolitorask.extension.calendar.CalendarWrapperLocal;
import org.multimedia.jolitorask.extension.calendar.CalendarWrapperLocalHome;

public class CalendarTimerSession implements SessionBean, TimedObject  {

	private static final long serialVersionUID = 1L;
	private SessionContext context;
	private TimerService timerService;
	private Timer timer;

    public void ejbTimeout(Timer timer) {
  
    	updateCalendars();
        System.out.println("Plannings mis a jour");
        
        timer.cancel();
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        cal.add(Calendar.WEEK_OF_YEAR, 1);
        timer = timerService.createTimer(cal.getTime(), "created timer");
        System.out.println("Prochaine mise a jour le : "+cal.getTime());
    }

    
    public void ejbCreate() throws CreateException{

    }

    public void startTimer() {
       System.out.println("TimerSessionBean: ejbCreate");
       System.out.println("TimerSessionBean: start createTimer ");
       timerService = context.getTimerService();
       timer = timerService.createTimer(500, "created timer");
    }
    

    
    
    public void setSessionContext(SessionContext sc) throws EJBException {
        context = sc;
     }

	
	
	public void ejbActivate() throws EJBException, RemoteException {}
	public void ejbPassivate() throws EJBException, RemoteException {}
	public void ejbRemove() throws EJBException, RemoteException {
		timer.cancel();
	}

	
	private void updateCalendars(){
		
		InitialContext ic;
		try {
			
			ic = new InitialContext();
			CalendarWrapperLocalHome home = (CalendarWrapperLocalHome) ic.lookup("calendarWrapperSessionLocal");
			CalendarWrapperLocal local = home.create();
			local.parseAll();
			
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
